import React, { useState, useEffect } from "react";
import {
  Button,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  Select,
  SelectItem,
  Calendar
} from "@nextui-org/react";
import { CreateShareParams, createShare } from "@/app/service/shareService.tsx";
import dayjs from "dayjs";
import { parseDate } from "@internationalized/date";

interface CreateShareModalProps {
  noteId: number;
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

// 客户端渲染钩子
function useClientOnly() {
  const [isMounted, setIsMounted] = useState(false);
  
  useEffect(() => {
    setIsMounted(true);
  }, []);
  
  return isMounted;
}

export default function CreateShareModal({ noteId, isOpen, onClose, onSuccess }: CreateShareModalProps) {
  const isMounted = useClientOnly();
  
  // 状态
  const [permission, setPermission] = useState<string>("READ");
  const [expiredAt, setExpiredAt] = useState<Date>(dayjs().add(7, "day").toDate());
  const [isLoading, setIsLoading] = useState(false);
  // 添加状态变量跟踪当前选中的过期时间选项
  const [selectedOption, setSelectedOption] = useState<number>(7);

  // 预设过期时间选项
  const expirationOptions = [
    { label: "1天", value: 1 },
    { label: "7天", value: 7 },
    { label: "30天", value: 30 },
    { label: "90天", value: 90 },
    { label: "永久有效", value: 3650 }, // 约10年，近似"永久"
  ];

  // 处理提交
  const handleSubmit = async () => {
    if (!noteId) return;
    
    setIsLoading(true);
    
    try {
      const params: CreateShareParams = {
        noteId,
        permission,
        expiredAt: dayjs(expiredAt).format("YYYY-MM-DDTHH:mm:ss")
      };
      
      await createShare(params);
      handleClose();
      
      if (onSuccess) {
        onSuccess();
      }
    } catch (error) {
      console.error("Failed to create share:", error);
    } finally {
      setIsLoading(false);
    }
  };

  // 选择预设过期时间
  const handleExpirationChange = (days: number) => {
    setSelectedOption(days); // 更新选中的选项
    setExpiredAt(dayjs().add(days, "day").toDate());
  };

  // 日历值变更
  const handleCalendarChange = (date: any) => {
    // 将Calendar组件的日期值转换为JavaScript Date
    const selectedDate = new Date(date.year, date.month - 1, date.day);
    setExpiredAt(selectedDate);
    // 清除按钮选中状态，因为用户选择了自定义日期
    setSelectedOption(-1);
  };

  // 关闭并重置表单
  const handleClose = () => {
    setPermission("READ");
    setExpiredAt(dayjs().add(7, "day").toDate());
    setSelectedOption(7); // 重置选中选项
    onClose();
  };

  // 确定日历的最小日期（今天）
  const today = new Date();
  const minDate = parseDate(`${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`);

  // 只在客户端渲染此组件
  if (!isMounted) {
    return null;
  }

  return (
    <Modal isOpen={isOpen} onClose={handleClose} size="md" classNames={{
      base: "max-w-md mx-auto",
      header: "border-b pb-2",
      footer: "border-t pt-2",
    }}>
      <ModalContent>
        <ModalHeader className="flex justify-center">创建笔记分享</ModalHeader>
        <ModalBody className="px-6 py-3">
          <div className="space-y-5">
            <Select
              label="分享权限"
              placeholder="选择分享权限"
              selectedKeys={[permission]}
              onChange={(e) => setPermission(e.target.value)}
              classNames={{
                trigger: "h-10",
              }}
            >
              <SelectItem key="READ" value="READ">只读</SelectItem>
              <SelectItem key="WRITE" value="WRITE">可编辑</SelectItem>
            </Select>
            
            <div className="flex flex-col gap-2">
              <label className="text-sm font-medium">过期时间</label>
              <div className="grid grid-cols-5 gap-2 mb-3 w-full">
                {expirationOptions.map((option) => (
                  <Button
                    key={option.value}
                    size="sm"
                    variant={selectedOption === option.value ? "solid" : "bordered"}
                    color={selectedOption === option.value ? "primary" : "default"}
                    onClick={() => handleExpirationChange(option.value)}
                    className="w-full h-9 min-w-0"
                  >
                    {option.label}
                  </Button>
                ))}
              </div>
              
              <div className="flex justify-center w-full">
                <Calendar 
                  color="primary"
                  minValue={minDate}
                  defaultValue={parseDate(dayjs(expiredAt).format("YYYY-MM-DD"))}
                  onChange={handleCalendarChange}
                  showShadow
                  className="mx-auto"
                  classNames={{
                    base: "rounded-lg",
                    months: "w-full",
                  }}
                />
              </div>
            </div>
          </div>
        </ModalBody>
        <ModalFooter className="flex justify-between px-6">
          <Button variant="bordered" onPress={handleClose} className="w-24">
            取消
          </Button>
          <Button color="primary" onPress={handleSubmit} isLoading={isLoading} className="w-24">
            创建分享
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
} 